package com.gao.config.security;

import com.gao.util.AuthenticationRedisUtils;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.util.List;

/**
 * @author gao
 * @date 2022/11/29 16:33:25
 */
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @NonNull
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @NonNull
    private AuthenticationFailureHandler authenticationFailureHandler;
    @NonNull
    AccessDeniedHandler accessDeniedHandler;
    @NonNull
    AuthenticationEntryPoint authenticationEntryPoint;
    @NonNull
    private AuthenticationRedisUtils authenticationRedisUtils;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 设置只有通过认证才能访问/api/greeting
        List<String> publicUrls = authenticationRedisUtils.getPublicUrls();
        http.authorizeRequests()
                .antMatchers(publicUrls.toArray(new String[]{}))
                .permitAll()
                .anyRequest()
                .authenticated();

        // 开启表单认证方式
        http.formLogin()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler);

        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);

        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);

        // 禁用会话
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 禁用csrf防御
        http.csrf().disable();
    }
}
